package com.nlgc365.designpattern.Chapter04_Pattern.Behavior.P05_State.Table;

import com.nlgc365.designpattern.Chapter04_Pattern.Behavior.P05_State.Framework.State;

/**
 * 作用: 事件以及事件之后的状态改变与动作
 */
public class MarioStateMachine {
    // 属性: 得分
    private int score;
    // 属性: 状态
    private State currentState;
    // 属性: 状态表
    private static final State[][] transitionTable = {
            {State.SUPER, State.CAPE, State.FIRE, State.SMALL},
            {State.SMALL, State.CAPE, State.FIRE, State.SMALL},
            {State.SMALL, State.SMALL, State.SMALL, State.SMALL},
            {State.SMALL, State.SMALL, State.SMALL, State.SMALL}
    };
    // 属性: 得分表
    // 问题: 在当前示例中, 属于action的逻辑只是数字运算, 如果是更加复杂的逻辑, 通过查表不容易实现.
    private static final int[][] actionTable = {
            {100, 200, 300, 0},
            {0, 200, 300, -100},
            {0, 0, 0, -200},
            {0, 0, 0, -300},
    };

    /**
     * 构造函数: 设定实例的初始化状态
     */
    public MarioStateMachine() {
        this.currentState = State.SMALL;
        this.score = 0;
    }

    /**
     * 函数: 动作 - 获得蘑菇
     */
    public void obtainMushRoom() {
        this.executeEvent(Event.GOT_MUSHROOM);
    }

    /**
     * 函数: 动作 - 获得披风
     */
    public void obtainCape() {
        this.executeEvent(Event.GOT_CAP);
    }

    /**
     * 函数: 动作 - 获得火焰
     */
    public void obtainFireFlower() {
        this.executeEvent(Event.GET_FIRE);

    }

    /**
     * 函数: 动作 - 遇到怪物
     */
    public void meetMonster() {
        this.executeEvent(Event.MEET_MONSTER);

    }

    /**
     * 函数: 执行事件
     *
     * @param event 事件
     */
    private void executeEvent(Event event) {
        int eventPosition = event.getValue();
        int statePosition = this.currentState.getValue();
        this.currentState = transitionTable[statePosition][eventPosition];
        this.score += actionTable[statePosition][eventPosition];
    }

    public int getScore() {
        return this.score;
    }

    public State getCurrentState() {
        return this.currentState;
    }

}
